<template>
    <div class="main-container">
        <!-- 表单 -->
        <el-card class="form-card">
            <el-header>
                <h2>{{ props.title }}</h2>
            </el-header>
            <el-main>
                <div class="form-container">
                    <el-form :model="form" label-width="100px">
                        <el-row :gutter="20">
                           
                            <el-col :span="12">
                                <el-form-item label="流域面积 (F, km²):">
                                    <el-input v-model="form.F" placeholder="流域面积" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="河道长度 (L, km):">
                                    <el-input v-model="form.L" placeholder="河道长度" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="河道比降 (J):">
                                    <el-input v-model="form.J" placeholder="河道比降" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="NDCD">
                                    <el-input v-model="form.NDCD" placeholder="NDCD" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="流域中心坐标 (经度, 纬度):">
                                    <el-input v-model="form.center_coords" placeholder="例: 112.0,34.0" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item>
                                    <el-button type="primary" @click="submitHandler">提交计算</el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
            </el-main>
        </el-card>

        <!-- 数据源切换 -->
        <el-row style="margin: 20px 0;">
            <el-button-group style="width: 100%;">
                <el-button type="primary" :plain="currentSource !== 'yellowRiver'" @click="switchSource('yellowRiver')">
                    黄河（沁河）小流域
                </el-button>
                <el-button type="primary" :plain="currentSource !== 'smallRiver'" @click="switchSource('smallRiver')">
                    小流域（漳卫南系）
                </el-button>
            </el-button-group>
        </el-row>

        <!-- 查询输入框 -->
        <el-input v-model="searchQuery" placeholder="请输入NDCD进行查询" style="margin-bottom: 20px; width: 100%;" clearable>
            <template #append>
                <el-button @click="handleSearch" icon="el-icon-search">搜索</el-button>
            </template>
        </el-input>

        <!-- 数据表格 -->
        <el-card>
            <h3>{{ currentSourceLabel }}（总条数: {{ filteredData.length }}）</h3>
            <el-table :data="filteredData.slice((currentPage - 1) * pageSize, currentPage * pageSize)" border
                style="width: 100%; margin-top: 10px;" @row-click="handleRowClick" @row-mouseenter="handleRowMouseEnter"
                @row-mouseleave="handleRowMouseLeave" :row-class-name="tableRowClassName" height='630'>
                <el-table-column prop="NDCD" label="NDCD" align="center" />
                <el-table-column label="详细信息" align="center">
                    <template #default="scope">
                        <el-button type="text" @click="scope.row.expanded = !scope.row.expanded">
                            {{ scope.row.expanded ? "收起" : "展开" }}
                        </el-button>
                        <div v-if="scope.row.expanded" class="expanded-info">
                            <p>流域面积 (F, km²): {{ scope.row.F }}</p>
                            <p>河道长度 (L, km): {{ scope.row.L }}</p>
                            <p>河道比降 (J): {{ scope.row.J }}</p>
                            <p>中心坐标: {{ scope.row.Lon }}, {{ scope.row.Lat }}</p>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination style="margin-top: 10px;" background layout="total, sizes, prev, pager, next, jumper"
                :current-page="currentPage" :page-sizes="[5, 10, 20, 50]" :page-size="pageSize"
                :total="filteredData.length" @current-change="handlePageChange"
                @size-change="handlePageSizeChange"></el-pagination>
        </el-card>
    </div>
</template>


<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import axios from "axios";
const emits = defineEmits(['submitHandler']);
const props = defineProps<{ title: string }>();
// 表单数据
const form = ref({
    F: "19.4012508392334", // 流域面积
    L: "12.027000427246094", // 河道长度
    J: "0.025053629651665688", // 河道比降
    center_coords: "111.31463623046875，34.75970458984375", // 流域中心坐标
    NDCD: "QDA000070131sA00", // 流域中心坐标
});

const submitHandler = function () {
    emits('submitHandler', form.value)
}

// 当前选中的数据源
const currentSource = ref("yellowRiver"); // 默认是黄河（沁河）小流域

// 查询关键字
const searchQuery = ref("");

// 数据源
const yellowRiverData = ref([]);
const smallRiverData = ref([]);

// 当前选中的行对象
const selectedRow = ref(null);

// 分页数据
const currentPage = ref(1);
const pageSize = ref(20); // 默认分页大小

// 动态获取当前数据源
const currentData = computed(() => {
    return currentSource.value === "yellowRiver"
        ? yellowRiverData.value
        : smallRiverData.value;
});

// 过滤后的数据
const filteredData = computed(() => {
    if (searchQuery.value) {
        return currentData.value.filter((item) =>
            item.NDCD.toLowerCase().includes(searchQuery.value.toLowerCase())
        );
    }
    return currentData.value;
});

// 数据源标签
const currentSourceLabel = computed(() => {
    return currentSource.value === "yellowRiver"
        ? "黄河（沁河）小流域"
        : "小流域（漳卫南系）";
});

// 切换数据源方法
function switchSource(source) {
    currentSource.value = source;
    currentPage.value = 1; // 切换数据源时重置分页
    searchQuery.value = ""; // 清空搜索内容
}

// 搜索按钮点击
function handleSearch() {
    // 模糊查询逻辑已经绑定在 `filteredData` 上，点击时直接触发筛选
}

// 分页事件处理
function handlePageChange(page) {
    currentPage.value = page;
}

// 改变分页大小
function handlePageSizeChange(size) {
    pageSize.value = size;
    currentPage.value = 1; // 分页大小改变时重置当前页
}

// 行点击事件 - 点击后将数据填入表单
function handleRowClick(row) {
    console.log(row)
    selectedRow.value = row;
    form.value.F = row.F;
    form.value.L = row.L;
    form.value.J = row.J;
    form.value.NDCD = row.NDCD;
    form.value.center_coords = `${Number(row.Lon)}，${Number(row.Lat)}`;

}

// 加载外部 JSON 数据
async function loadData() {
    try {
        const yellowRiverResponse = await axios.get("/yellowRiver.json");
        yellowRiverData.value = yellowRiverResponse.data.map((item) => ({
            ...item,
            expanded: false,
        }));

        const smallRiverResponse = await axios.get("/smallRiver.json");
        smallRiverData.value = smallRiverResponse.data.map((item) => ({
            ...item,
            expanded: false,
        }));
    } catch (error) {
        console.error("加载数据失败:", error);
    }
}

const hoveredRowIndex = ref(null);

function handleRowMouseEnter(row, rowIndex) {
    hoveredRowIndex.value = rowIndex; // 记录悬浮行的索引
}

function handleRowMouseLeave() {
    hoveredRowIndex.value = null; // 清除悬浮行索引
}

function tableRowClassName({ row, rowIndex }) {
    if (selectedRow.value === row) {
        return "selected-row"; // 选中行样式
    }
    if (hoveredRowIndex.value === rowIndex) {
        return "hovered-row"; // 悬浮行样式
    }
    return "";
}


// 组件加载时调用
onMounted(() => {
    loadData();
});
</script>

<style scoped lang="scss">
.main-container {
    padding: 10px;
}

h3 {
    font-size: 18px;
    margin-bottom: 10px;
}

.el-table {
    border-radius: 5px;
    overflow: hidden;
}

.el-table th {
    font-weight: bold;
    color: #606266;
}

.el-table td {
    padding: 10px 8px;
}

.expanded-info {
    padding: 10px;
    border-radius: 5px;
    margin-top: 10px;
}

.el-button {
    font-size: 14px;
}

/* 行样式 */
.selected-row {
    background-color: #e6f7ff !important;
    /* 选中行高亮 */
}

.hovered-row {
    background-color: #f5f5f5 !important;
    /* 悬浮行高亮 */
}
</style>
